package org.tinygroup.cepcore.util;

import java.util.HashMap;
import java.util.Map;

import org.tinygroup.context.Context;

public class ThreadContextUtil {
	private static InheritableThreadLocal<Map<String, Object>> threadVariableMap = new InheritableThreadLocal<Map<String, Object>>(){
		protected Map<String, Object> childValue(
				Map<String, Object> parentValue) {
			if (parentValue == null) {
				return null;
			}
			return new HashMap<String, Object>(parentValue);
		}
	};
//	private final static ThreadLocal<Context> context = new ThreadLocal<Context>();
	public final static String THREAD_CONTEXT_KEY = "tiny_sys_service_thread_context";
	public final static String LOGGER_THREADLOCAL_KEY = "logger_threadlocal_key";

	/**
	 * 获取当前上下文context
	 * @return
	 */
	private static Map<String, Object> getCurrentThreadContext() {
		Map<String, Object> currentcontext = threadVariableMap.get();
		if (currentcontext == null) {
			currentcontext = new HashMap<String, Object>();
			threadVariableMap.set(currentcontext);
		}
		return currentcontext;
	}

	public static Object get(String name) {
		return getCurrentThreadContext().get(name);
	}

	public static void put(String name, Object value) {
		getCurrentThreadContext().put(name, value);
	}

	public static Object remove(String name) {
		return getCurrentThreadContext().remove(name);
	}

	public static void putCurrentThreadContextIntoContext(Context mainContext) {
		Map<String, Object>  currentContext = getCurrentThreadContext();
		mainContext.put(THREAD_CONTEXT_KEY, currentContext);
//		mainContext.putSubContext(THREAD_CONTEXT_KEY, currentContext);
	}
	public static void parseCurrentThreadContext(Context mainContext){
		if(!mainContext.exist(THREAD_CONTEXT_KEY)){
			return ;
		}
		Map<String, Object> currentContext = mainContext.remove(THREAD_CONTEXT_KEY);
//		Context currentContext = mainContext.getSubContext(THREAD_CONTEXT_KEY);
		if(currentContext!=null){
			threadVariableMap.set(currentContext);
		}
	}
}